<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="分公司负责人" size="small" label-width="100px">
            <el-input v-model="searchForm.legalPerson"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="address">
          <el-form-item label="地区搜索" size="small">
            <el-select v-model="searchForm.provinceId" placeholder="请选择省份" @change="provinceChange">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="(item,key) in pca[86]"
                :key="key"
                :label="item"
                :value="key">
              </el-option>
            </el-select>
            <el-select size="small" v-model="searchForm.cityId" placeholder="请选择城市">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="(item,key) in pca[searchForm.provinceId]"
                :key="key"
                :label="item"
                :value="key">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px" @close="closeOuterVisible">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-form-item prop="companyName" label="分公司名称" size="small">
            <el-input type="text" v-model="teamRow.companyName"></el-input>
          </el-form-item>
          <el-form-item prop="legalPerson" label="分公司负责人" size="small">
            <el-input type="text" v-model="teamRow.legalPerson"></el-input>
          </el-form-item>
          <el-form-item prop="address" label="所在地址" size="small">
            <area-cascader v-model="teamRow.addressId" v-if="isAddress" placeholder="请选择省市" :data="pca"
                           @change="addressChange()"></area-cascader>
            <el-input type="textarea" v-model="teamRow.address" placeholder="请填写详细地址"></el-input>
          </el-form-item>
          <el-form-item prop="processPerson" label="办理负责人" size="small">
            <el-input type="text" v-model="teamRow.processPerson"></el-input>
          </el-form-item>
          <el-form-item prop="finshTime" label="预计完成时间" size="small">
            <el-date-picker
              v-model="teamRow.finshTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="开户行" size="small">
            <el-input type="text" v-model="teamRow.openingBank"></el-input>
          </el-form-item>
          <el-form-item label="开户账号" size="small">
            <el-input type="text" v-model="teamRow.bankAccount"></el-input>
          </el-form-item>
          <el-form-item label="文件上传" size="small">
            <input type="file" ref='infoFile' @change="getInfoFile($event)">
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editSchedule(scope.row)"
            type="text"
            size="small">
            进度日志管理
          </el-button>
           <a v-if="scope.row.filePath" target="_blank" :href="GLOBAL.filePathUrl+ encodeURI(scope.row.filePath)">下载</a>
          <el-button
            @click.native.prevent="editTeam(scope.row.buildId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; schedule: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="scheduleTitle" :visible.sync="scheduleVisible" width="600px">
      <el-form ref="schedule" :rules="scheduleRules" :model="schedule" label-width="100px">
        <el-form-item prop="companyName" label="分公司名称" size="small">
          <el-input type="text" v-model="schedule.companyName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="occurrenceTime" label="发生时间" size="small">
          <el-date-picker
            v-model="schedule.occurrenceTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="stepDesc" label="进度描述" size="small">
          <el-input type="textarea" v-model="schedule.stepDesc"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="warning" size="small" @click="submitSchedule('schedule',scheduleType)">
        {{scheduleBtn}}
      </el-button>
      <my-table
        :data="scheduleData"
        :col-configs="scheduleConfigs"
        v-loading="scheduleLoading"
        :height="200"
      >
        <el-table-column
          slot="scheduleOpt"
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="selectSchedule(scope.row.logId)"
              type="text"
              size="small">
              修改
            </el-button>
            <el-popover
              placement="top"
              width="160"
              :ref="`schedule-${scope.$index}`"
            >
              <p>确定删除这条数据吗?</p>
              <div style="text-align: right; schedule: 0">
                <el-button size="mini" type="text" @click="$refs[`schedule-${scope.$index}`].doClose()">取消</el-button>
                <el-button type="primary" size="mini" @click.native.prevent="deleteSchedule(scope)">确定</el-button>
              </div>
              <el-button type="text" size="small" slot="reference" v-popover:schedule-${scope.$index}>删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </my-table>
    </el-dialog>
  </div>
</template>

<script>
  import {
    deleteFiliale,
    deleteSchedule,
    getFilialeList,
    getScheduleList,
    insertFiliale,
    insertSchedule,
    selectFiliale,
    selectSchedule,
    updateFiliale,
    updateSchedule
  } from '@/api/filiale'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const preFinishTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :min-width="colConfig.minWidth">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const dateCompleted = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'companyName', label: '分公司名称', minWidth: '20%', fixed: true },
          { prop: 'address', label: '地区', minWidth: '20' },
          { prop: 'legalPerson', label: '分公司法人', minWidth: '15%' },
          { prop: 'processPerson', label: '办理负责人', minWidth: '15%' },
          { prop: 'preFinishTime', label: '预计完成时间', minWidth: '15%', component: preFinishTime },
          { prop: 'openingBank', label: '开户行', minWidth: '15%' },
          { prop: 'bankAccount', label: '开户账号', minWidth: '15%' },
          { slot: 'opt' }
        ],
        scheduleConfigs: [
          { prop: 'stepDesc', label: '进度描述', width: '200' },
          { prop: 'dateCompleted', label: '发生时间', width: '150', component: dateCompleted },
          { slot: 'scheduleOpt' }
        ],
        searchForm: {
          provinceId: '',
          cityId: ''
        },
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        scheduleLoading: true,
        dialogTitle: '新增品牌构建支出',
        scheduleTitle: '分公司筹建进度日志信息管理',
        scheduleType: 1,
        scheduleBtn: '添加进度日志',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        schedule: {},
        scheduleClear: {},
        tableData: [],
        scheduleData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        scheduleVisible: false,
        isAddress: false, // 地区新增 修改 摧毁 生成组件
        isRender: false, // 判断地区是否编辑
        pca: pca,
        rules: {
          companyName: [
            { required: true, message: '请输入分公司名称', trigger: 'change' }
          ],
          legalPerson: [
            { required: true, message: '请输入分公司法人', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请输入地址', trigger: 'change' }
          ],
          processPerson: [
            { required: true, message: '请输入办理负责人', trigger: 'change' }
          ],
          finshTime: [
            { required: true, message: '请选择预计完成时间', trigger: 'change' }
          ]
        },
        scheduleRules: {
          companyName: [
            { required: true, message: '请输入分公司名称', trigger: 'change' }
          ],
          occurrenceTime: [
            { required: true, message: '请选择发生时间', trigger: 'change' }
          ],
          stepDesc: [
            { required: true, message: '请输入进度描述', trigger: 'change' }
          ]
        },
        visible: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getFilialeList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      scheduleFetchData() {
        this.scheduleLoading = true
        getScheduleList(this.schedule).then(response => {
          this.scheduleData = response.responseBody
          this.scheduleLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
        console.log(this.pca[86])
      },
      cityChange() {
        console.log(this.pca[this.searchForm.provinceId])
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.isAddress = true
        this.dialogTitle = '新增分公司筹建进度日志'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.dialogType = 1
        if (this.$refs.infoFile) {
          this.$refs.infoFile.value = ''
        }
      },
      editTeam(buildId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isAddress = true
        this.isRender = true
        this.dialogTitle = '修改分公司筹建进度日志'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          buildId: buildId
        }
        selectFiliale(params).then(response => {
          this.teamRow = response.responseBody
          this.$set(this.teamRow, 'finshTime', formatDate(new Date(this.teamRow.preFinishTime), 'yyyy-MM-dd'))
          this.teamRow.addressId = [this.teamRow.provinceId.toString(), this.teamRow.cityId.toString()]
        })
        if (this.$refs.infoFile) {
          this.$refs.infoFile.value = ''
        }
      },
      closeOuterVisible() {
        this.isAddress = false
      },
      submitForm(formName) {
        const params = new FormData()
        if (!this.dialogType) {
          params.append('buildId', this.teamRow.buildId)
        }
        params.append('companyName', this.teamRow.companyName)
        params.append('legalPerson', this.teamRow.legalPerson)
        params.append('provinceId', this.teamRow.provinceId)
        params.append('cityId', this.teamRow.cityId)
        params.append('address', this.teamRow.address)
        params.append('processPerson', this.teamRow.processPerson)
        params.append('finshTime', this.teamRow.finshTime)
        params.append('openingBank', this.teamRow.openingBank ? this.teamRow.openingBank : '')
        params.append('bankAccount', this.teamRow.bankAccount ? this.teamRow.bankAccount : '')
        params.append('remark', this.teamRow.remark ? this.teamRow.remark : '')
        if (this.teamRow.file) {
          params.append('file', this.teamRow.file)
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              insertFiliale(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.isAddress = false
                this.fetchData()
              })
            } else {
              updateFiliale(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.isAddress = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          buildId: scope.row.buildId,
          isDel: 1
        }
        deleteFiliale(params).then(response => {
          this.fetchData()
        })
      },
      editSchedule(row) {
        this.scheduleVisible = true
        this.scheduleClear.buildId = row.buildId
        this.scheduleClear.companyName = row.companyName
        this.schedule = JSON.parse(JSON.stringify(this.scheduleClear))
        this.scheduleFetchData()
        if (this.$refs['schedule']) {
          this.$refs['schedule'].resetFields()
        }
        this.scheduleType = 1
        this.scheduleBtn = '新增进度日志'
      },
      selectSchedule(logId) {
        this.scheduleType = 0
        this.scheduleBtn = '保存进度日志'
        const prarms = {
          logId: logId
        }
        selectSchedule(prarms).then(response => {
          this.schedule = response.responseBody
          this.$set(this.schedule, 'occurrenceTime', formatDate(new Date(this.schedule.dateCompleted), 'yyyy-MM-dd'))
        })
      },
      submitSchedule(scheduleName, type) {
        const params = JSON.parse(JSON.stringify(this.schedule))
        console.log(params)
        delete params.companyName
        this.$refs[scheduleName].validate((valid) => {
          if (valid) {
            if (type) {
              insertSchedule(params).then(response => {
                this.scheduleFetchData()
                this.schedule = JSON.parse(JSON.stringify(this.scheduleClear))
              })
            } else {
              updateSchedule(params).then(response => {
                this.scheduleFetchData()
                this.schedule = JSON.parse(JSON.stringify(this.scheduleClear))
                this.scheduleType = 1
                this.scheduleBtn = '新增进度日志'
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteSchedule(scope) {
        this.$refs[`schedule-${scope.$index}`].doClose()
        const params = {
          logId: scope.row.logId,
          isDel: 1
        }
        deleteSchedule(params).then(response => {
          this.scheduleFetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        if (!this.isRender) {
          this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
        } else {
          this.isRender = false
        }
      },
      getInfoFile(event) {
        this.teamRow.file = event.target.files[0]
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      schedule-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        schedule: 0 20px;
      }
      .el-dialog {
        textarea {
          schedule-top: 10px;
        }
        .el-checkbox {
          schedule-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          schedule-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
